 //
//  MeInfoMainVC.m
//  MPTLive
//
//  Created by caixun on 16/1/27.
//  Copyright © 2016年 Jeakin. All rights reserved.
//

#import "MeInfoMainVC.h"
#import "MeInfoMainCell.h"
#import "MeInfoMainHeadView.h"
#import "GuanZhuListVC.h"
#import "NSString+MPTString.h"
#import "MPTLoginUser.h"
#import <MPTLivePlayerVC.h>
#import "FootRefreshView.h"
#import "HeadRefreshView.h"
#import "MPTEditUserDataViewController.h"
#import "MPTMyOperateView.h"
#import "MPTChannelModel.h"
#import "MPTLiveShareView.h"
#import <UIWindow+MPTWindow.h>
#import "MPTPlayerVC.h"

@interface MeInfoMainVC ()
<
UITableViewDataSource,
UITableViewDelegate
>


@property (nonatomic, strong) UITableView *tableV;

@property (nonatomic, strong) MeInfoMainHeadView *headView;

/// 视频列表数据
@property (nonatomic, strong) NSMutableArray *aryData;

@property (nonatomic, assign) NSInteger intPage;

@end


@implementation MeInfoMainVC


#pragma mark - ********************** View Lifecycle **********************

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initVariable]; /// 初始化变量
    [self initViews]; /// 初始化界面
    
    if (!_dicData)
    {
        [self req_URL_shot_channel]; /// 发送请求
    }
    else
    {
        [self.aryData addObjectsFromArray:_dicData[@"result"]];
        [self.headView setData:self.dicData];
        /// 名称
        self.superNavBarView.labelTitle.text =self.dicData[@"header"][@"nick"];
    }
    
    [self regNotification]; /// 注册消息
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[TPTabBarManager share] showBottomView:NO animation:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    // 一定要关注这个函数是否被执行了！！！
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark - ********************** Init All Views **********************

- (void)initVariable
{
    _intPage = 1;
    _aryData = [NSMutableArray array];
}

- (void)initViews
{
    /// 根据界面情况，决定是单独写函数，或直接写Views
    [self initMainViews];
    
    [self initNavView]; /// 初始化Nav导航栏
}

- (void)initNavView
{
    /// 创建导航栏
    [self createNavBarViewWithTitle:@""];
    self.superNavBarView.backgroundColor = [UIColor clearColor];
    self.superNavBarView.labelTitle.hidden = YES;
    self.superNavBarView.labelTitle.textColor = RGBAAllColor(0xFFFFFF, 1);
    self.superNavBarView.viewBottomLine.backgroundColor = [UIColor clearColor];
    self.superNavBarView.imgvBackGround.image = [UIImage imageNamed:@"mengchengshang"];
    /// 创建左侧按钮
    [self createNavLeftBtnWithItem:@""
                            target:self
                            action:@selector(btnClickBack:)];
    [self.superNavBarView.btnLeft setImage:[UIImage imageNamed:@"baifanhui"] forState:UIControlStateNormal];
}

- (void)initMainViews
{
    _tableV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, screenW, screenH) style:UITableViewStylePlain];
    _tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableV.showsHorizontalScrollIndicator = NO;
    _tableV.showsVerticalScrollIndicator = NO;
    _tableV.delegate = self;
    _tableV.dataSource = self;
    [self.view addSubview:_tableV];
    
    _headView = [[MeInfoMainHeadView alloc] initWithFrame:CGRectMake(0, 0, screenW, screenW + 64)];
    [_headView isShowBianJi:!ZB_Str_Is_Valid(_suid)];
    
    /// 点击粉丝 关注 编辑 或者 的block
    __weak MeInfoMainVC *weakSelf = self;
    [_headView setBlock:^(MeInfoMainHeadViewClicked MeInfoMainHeadViewEnum){
        if (MeInfoMainHeadViewEnum == FenShiB)
        {
            GuanZhuListVC *vc = [[GuanZhuListVC alloc] init];
            vc.fromeType = FenShi;
            /// 有suid 是登陆者看别人的
            if (ZB_Str_Is_Valid(_suid))
            {
                vc.suid = weakSelf.suid;
            }
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
        else if (MeInfoMainHeadViewEnum == GuanZhuA)
        {
            GuanZhuListVC *vc = [[GuanZhuListVC alloc] init];
            vc.fromeType = GuanZhu;
            /// 有suid 是登陆者看别人的
            if (ZB_Str_Is_Valid(_suid))
            {
                vc.suid = weakSelf.suid;
            }
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
        else//编辑 或者关注
        {
            if (ZB_Str_Is_Valid(_suid))
            {
                /// 关注 请求关注接口
                [weakSelf req_GuanZhuWithUserId:weakSelf.suid relation:[weakSelf.dicData[@"relation"] integerValue]isBool:([weakSelf.dicData[@"relation"] integerValue] !=0 && [weakSelf.dicData[@"relation"] integerValue] !=2) ? NO : YES];
                
                /// 改变本地数据
                if (([weakSelf.dicData[@"relation"] integerValue] !=0 && [weakSelf.dicData[@"relation"] integerValue] !=2))
                {
                    [weakSelf.dicData setValue: @(1) forKey:@"relation"];
                }
                else
                {
                    [weakSelf.dicData setValue: @(2) forKey:@"relation"];
                }
            }
            else
            {
                /// 编辑
                MPTEditUserDataViewController *editVC = [[MPTEditUserDataViewController alloc] init];
                [weakSelf.navigationController pushViewController:editVC animated:YES];
            }
        }
    }];
    _tableV.tableHeaderView = _headView;
    
    // 下拉刷新和上拉分页
    [_tableV addFootRefreshViewWithTarget:self advanceRefresh:YES action:@selector(fectchMoreData)];
    [_tableV.YX_FootRefreshView addCustomView:[FootRefreshView createFootRefresh]];
    
    [_tableV addHeadRefreshViewWithTarget:self action:@selector(fectchNewData)];
    [_tableV.YX_HeadRefreshView addCustomView:[HeadRefreshView createHeadRefresh]];
}


#pragma mark - ********************** Functions **********************

- (void)deleteVieo
{
    /// 拼接改变的数据
    NSMutableDictionary *mdict = [NSMutableDictionary dictionaryWithDictionary:_dicData];
    [mdict setValue:_aryData forKey:@"result"];
    NSDictionary *dict = [NSDictionary dictionaryWithDictionary:mdict];
    if (self.block)
    {
        self.block(dict);
    }
}

- (void)fectchNewData
{
    self.intPage = 1;
    [self req_URL_shot_channel];
}

- (void)fectchMoreData
{
    self.intPage++;
    [self req_URL_shot_channel];
}

#pragma mark - 注册消息

- (void)regNotification
{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fectchNewData) name:@"MPTLIVE_RequestNotification" object:nil];

}

#pragma mark - demo

/// 分享操作
- (void)shareFun:(NSIndexPath *)indexPath
{
    /// 根据suid判断是自己还是主播
    if (ZB_Str_Is_Valid(_suid))
    {
        MPTChannelModel *modelZhuBo = [MPTChannelModel fromJSONDictionary:[_aryData[indexPath.row] objectForKey:@"channel"] error:nil];
        
        NSString *liveString =  @"0";//_isLiveFrome ? @"1" : @"0";
        
        //shareImage：分享出去的图片 isHost：是否是主播，0不是   1是主播     isLive：是否为直播 isLive为1   录播为0
        NSDictionary *weiboSharePara = @{@"shareImage":modelZhuBo.videoImage,@"isHost":liveString,@"model":modelZhuBo,@"isLive":liveString};

        MPTLiveShareView *  liveShareView= [[MPTLiveShareView alloc] initWithFrame:self.view.bounds];
        liveShareView.strShareUrl = [NSString stringWithFormat:@"http://www.miaopai.com/show/%@.htm", modelZhuBo.scid];
        [liveShareView initWithLiveChannel:weiboSharePara];
        [self.view addSubview:liveShareView];
        [self.view bringSubviewToFront:liveShareView];
    }
    else
    {
        MPTChannelModel *modelZhuBo = [MPTChannelModel fromJSONDictionary:[_aryData[indexPath.row] objectForKey:@"channel"] error:nil];
        NSString *liveString =  @"1";//_isLiveFrome ? @"1" : @"0";
        
        //shareImage：分享出去的图片 isHost：是否是主播，0不是   1是主播     isLive：是否为直播 isLive为1   录播为0
        NSDictionary *weiboSharePara = @{@"shareImage":modelZhuBo.videoImage,@"isHost":liveString,@"model":modelZhuBo,@"isLive":liveString};
        
        MPTMyOperateView *viewShare = [[MPTMyOperateView alloc] initWithFrame:self.view.bounds];
        viewShare.strShareUrl = [NSString stringWithFormat:@"http://www.miaopai.com/show/%@.htm", modelZhuBo.scid];
        viewShare.indexpath = indexPath;
        /// 删除的block
        __weak MeInfoMainVC  *weakSelf = self;
        [viewShare setBlock:^(NSIndexPath *indexpath)
         {
             /// 请求删除视频接口
             [weakSelf req_DeleteVideo:indexpath];
             /// 移除数据源
             [weakSelf.aryData removeObjectAtIndex:indexpath.row];
             [weakSelf.tableV deleteRowsAtIndexPaths:@[indexpath] withRowAnimation:UITableViewRowAnimationNone];
             [weakSelf.tableV reloadData];
            
             /// 删除回调给上一页
             [weakSelf deleteVieo];
            
         }];
        [viewShare initWithLiveChannel:weiboSharePara andView:self.view];
        [self.view addSubview:viewShare];
        [self.view bringSubviewToFront:viewShare];
    }
}


#pragma mark - ********************** Button Touch Event **********************

- (void)btnClickBack:(TPButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - ********************** Net Connection Event **********************

#pragma mark - 请求 xxx

- (void)req_URL_shot_channel
{
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSDictionary *paraDic = @{@"os":@"ios",
                              @"page":@(_intPage),
                              @"version":ZB_Str_Protect(version),
                              @"unique_id":ZB_Str_Protect([NSString MPTIdentifierString]),
                              @"showType":@"2",
                              @"suid":_suid == nil ? ZB_Str_Protect([MPTLoginUser unArchiver].suid) : _suid,
                              @"per" :@"10"};
    
    __weak MeInfoMainVC *Weakself = self;
    [[MPTHttpClient sharedMPHTTPClient] getPath:@"m/shot_channel.json" parameters:paraDic queuePriority:NSOperationQueuePriorityNormal cacheRequest:NO  success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if ([responseObject isKindOfClass:[NSDictionary class]])
        {
            if ([responseObject[@"status"] integerValue] == 200)
            {
                if (Weakself.intPage == 1)
                {
                    [Weakself.tableV.YX_HeadRefreshView endRefreshing];
                    [Weakself.aryData removeAllObjects];
                    Weakself.dicData = [NSMutableDictionary dictionaryWithDictionary:responseObject];
                    [Weakself.headView setData:Weakself.dicData];
                    /// 名称
                    Weakself.superNavBarView.labelTitle.text =Weakself.dicData[@"header"][@"nick"];
                }
                [Weakself.aryData addObjectsFromArray:responseObject[@"result"]];
            }
            [Weakself.tableV reloadData];
        }
        
        /// 取消刷新状态
        [Weakself.tableV.YX_FootRefreshView noDataRefresh:NO];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        /// 取消刷新状态
        [Weakself.tableV.YX_HeadRefreshView endRefreshing];
        [Weakself.tableV.YX_FootRefreshView noDataRefresh:NO];
        
    } cached:nil];
}

/// 删除视频的炒作
- (void)req_DeleteVideo:(NSIndexPath *)indexpath
{
    NSDictionary *dic = [NSDictionary dictionaryWithDictionary:_aryData[indexpath.row]];
    [[MPTHttpClient sharedMPHTTPClient] deleteVideoScid:ZB_Str_Protect(dic[@"channel"][@"scid"])
                                                success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject)
    {
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {
        
    }];

}

/// 关注取消关注
- (void)req_GuanZhuWithUserId:(NSString *)strUserId relation:(NSInteger)relation isBool:(BOOL)isBool
{
    [[MPTHttpClient sharedMPHTTPClient]changeUserRelation:isBool suid:strUserId current:relation success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
    }];
    
}


#pragma mark - ********************** Delegate Event **********************

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
           editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath      //当在Cell上滑动时会调用此函数
{
    
    if(!ZB_Str_Is_Valid(_suid))
    {
        return  UITableViewCellEditingStyleDelete;  //返回此值时,Cell会做出响应显示Delete按键,点击Delete后会调用下面的函数,别给传递UITableViewCellEditingStyleDelete参数
    }
    else
    {
        return  UITableViewCellEditingStyleNone;   //返回此值时,Cell上不会出现Delete按键,即Cell不做任何响应
    }

}

- (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath//对选中的Cell根据editingStyle进行操作
{
    /// 请求删除接口
    [self req_DeleteVideo:indexPath];
    
    /// 删除数据源
    [_aryData removeObjectAtIndex:indexPath.row];
    
    /// 删除
    [_tableV deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    
    /// 删除回调给上一页
    [self deleteVieo];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [MeInfoMainCell GetHeight];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _aryData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MeInfoMainCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeInfoMainCell"];
    if (!cell)
    {
        cell = [[MeInfoMainCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MeInfoMainCell"];
    }
    
    cell.indexpath = indexPath;
    cell.dicData = _aryData[indexPath.row];
    
    __weak MeInfoMainVC *weakSelf = self;
    
    [cell setBlock:^(NSIndexPath *indexpath){
        
        [weakSelf shareFun:indexpath];
        
    }];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    /// 获取数据
    NSDictionary *dic = _aryData[indexPath.row][@"channel"];
    if (dic[@"scid"])
    {
        /// 视频状态
        if ([dic[@"liveStatus"] integerValue] == 1)
        {
            /// 视频中心类
            [[TPTabBarManager share] showBottomView:NO animation:YES];
            MPTLivePlayerVC *vc = [[MPTLivePlayerVC alloc] initWithScid:dic[@"scid"]];
            vc.strImageUrl = [NSString stringWithFormat:@"%@%@",dic[@"pic"][@"base"],dic[@"pic"][@"m"]];
            [[UIApplication sharedApplication].keyWindow.visibleViewController presentViewController:vc animated:YES completion:nil];

        }
        else
        {
            MPTPlayerVC *vc = [[MPTPlayerVC alloc] initWithScid:dic[@"scid"]];
            vc.strImageUrl = [NSString stringWithFormat:@"%@%@",dic[@"pic"][@"base"],dic[@"pic"][@"m"]];
            /// 获取视频的url
            if ([dic[@"liveUrls"] isKindOfClass:[NSArray class]])
            {
                if ([dic[@"liveUrls"] count] > 0)
                {
                    vc.strVideoUrl = [dic[@"liveUrls"] firstObject];
                }
            }
            [[UIApplication sharedApplication].keyWindow.visibleViewController presentViewController:vc animated:YES completion:nil];
        }
    }
    else
    {
        
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    /// 标题显示逻辑
    if (scrollView.contentOffset.y >= screenW)
    {
        self.superNavBarView.labelTitle.hidden = NO;
    }
    else
    {
        self.superNavBarView.labelTitle.hidden = YES;
    }
}

#pragma mark - ********************** Notification Event **********************

#pragma mark - 通知 xxx



@end
